<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>文件上传</h1>
<!--上传文件，必须给form表单添加enctype="multipart/form-data"
表示编码类型为多部分数据-->
<form action="" enctype="multipart/form-data">
    <input type="text" name="intro" placeholder="图片介绍"><br>
    <input type="file" name="picFile"><br>
    <input type="button" value="上传" @click="upload()"><br>

    <hr>
    <div v-for="pic in arr">
        <h2>{{pic.intro}}</h2>
        <img :src="pic.url" width="200px" alt="">
    </div>
</form>
<!--引入axios和vue-->
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
    let v = new Vue({
        el:"form",
        data:{
            arr:[]
        },
        methods:{
            upload:function () {
                //获取form表单数据
                let data = new FormData(document.querySelector("form"));
                //判断是否选择了图片
                if(data.get("picFile").name==""){
                    alert("请选择图片后再上传！")
                    //没有选择图片，则结束方法的执行
                    return;
                }
                //文件上传必须使用post请求
                axios.post("/upload",data).then(function () {
                    alert("上传成功");
                    location.reload();
                })
            }
        },
        created:function () {
            axios.get("/select").then(function (res) {
                v.arr = res.data;
            })
        }
    })

</script>
</body>
</html>